﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace Client
{
    class Program
    {
        static Socket client;
        static void Main(string[] args)
        {
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.Connect(IPAddress.Parse("192.168.0.100"), 2001);
            Console.WriteLine("Connected");
            ThreadPool.QueueUserWorkItem(new WaitCallback(Recive),client);
            client.Send(new byte[] {0,5,0,0,0});

            
            
            Console.ReadLine();
           
        }

        static void Recive(object state)
        {
            Socket sock = state as Socket;
            byte[] buffer=new byte[1];
            while (true)
            {
                if (sock.Available != 0 && Process==false)
                {
                    //ReadHeader
                    sock.Receive(buffer);
                    switch ((MSG)buffer[0])
                    {
                        case MSG.FILE_SIZE:
                            buffer = new byte[8];
                            sock.Receive(buffer);
                            Size = BitConverter.ToInt64(buffer,0);
                            reader = new StreamWriter("_1.bin");
                            Console.WriteLine("Size :" + Size);
                            break;
                        case MSG.BEGIN_SEND:
                            Process = true;
                            Console.WriteLine("Begin Recive");
                            break;
                    }
                }
                else if (sock.Available != 0 && Process == true)
                {
                    buffer = new byte[8000];
                    int leng=sock.Receive(buffer);
                    if (sock.Available == 0)
                    {
                        if (leng != 0)
                            reader.BaseStream.Write(buffer, 0, leng);
                        reader.Close();
                        Process = false;
                        Console.WriteLine("Recive Complete");
                    }
                    else
                        reader.BaseStream.Write(buffer, 0, leng);
                }
                if(!Process)
                    Thread.Sleep(200);
            }
        }

        static bool Process=false;
        static StreamWriter reader;
        static Int64 Size;
    }
}
